#include "ImageProcessor.h"
#include "afterdetect.h"
#include "autorunprocess.h"
#include "cvalgedgedetection.h"
#include "detectcachemodel.h"
#include "floorsetting.h"
#include "gpiocontroller.h"
#include "mousetracker.h"
#include "tools.h"
#include "afterdetect.h"
#include "detectcachemodel.h"
void AutoRunProcess::calculateAdjustedRange(QVector<double>& moveDistanceList) {
    if (moveDistanceList.isEmpty()) {
        qWarning() << "moveDistanceList is empty.";
        return; // Exit early if the list is empty
    }

    // Step 1: 计算均值
    double sum = 0.0;
    for (double value : moveDistanceList) {
        sum += value;
    }
    double mean = sum / moveDistanceList.size();

    // Step 2: 计算标准差
    double variance = 0.0;
    for (double value : moveDistanceList) {
        variance += std::pow(value - mean, 2);
    }
    double stdDev = std::sqrt(variance / moveDistanceList.size());

    // Step 3: 设定阈值，过滤掉差别过大的值
    double threshold = 3.0; // 设定阈值为均值 ± 3倍标准差
    QVector<double> filteredList;

    // 过滤掉那些距离均值超过3倍标准差的数据点
    for (double value : moveDistanceList) {
        if (std::abs(value - mean) <= threshold * stdDev) {
            filteredList.append(value);
        }
    }

    // 如果过滤后列表为空，返回警告
    if (filteredList.isEmpty()) {
        qWarning() << "No valid values in the moveDistanceList after filtering.";
        return;
    }


    double filteredSum = 0.0;
    for (double value : filteredList) {
        filteredSum += value;
    }
    double filteredMean = filteredSum / filteredList.size();

    double diff =  PreProcessor::getInstance().monitorImg_.getRoi().width *
                  ImageProcessor::getInstance().get_moveDistanceRed();
    // Step 3: 将最大值增加差值的10%，将最小值减少差值的10%
    moveDistanceMax = filteredMean + diff;
    moveDistanceMin = filteredMean - diff;


}

double calculateMinValueWithExclusion(QVector<double>& FabricSpacingList) {
    // Step 1: 计算均值
    int sum = 0;
    for (int value : FabricSpacingList) {
        sum += value;
    }
    double mean = sum / static_cast<double>(FabricSpacingList.size());

    // Step 2: 计算标准差
    double variance = 0.0;
    for (int value : FabricSpacingList) {
        variance += std::pow(value - mean, 2);
    }
    double stdDev = std::sqrt(variance / FabricSpacingList.size());

    // Step 3: 排除差别过大的值
    QVector<int> filteredList;
    for (int value : FabricSpacingList) {
        if (std::abs(value - mean) <= 2 * stdDev) {
            filteredList.append(value);
        }
    }

    // Step 4: 计算最小值
    if (filteredList.isEmpty()) {
        qWarning() << "Filtered list is empty.";
        return -1;  // 或者根据需要返回一个错误值
    }

    int minValue = filteredList[0];
    for (int value : filteredList) {
        if (value < minValue) {
            minValue = value;
        }
    }

    return minValue;
}

AutoRunProcess::AutoRunProcess(QObject *parent)
    : QObject(parent), receivedIO1(0) {
    IO1debounceTimer = new QTimer(this);
    IO1debounceTimer->setSingleShot(true);
    IO2debounceTimer = new QTimer(this);
    IO2debounceTimer->setSingleShot(true);

    // connect(&GpioController::getInstance(), &GpioController::shortageGrigger,
    //         this, &AutoRunProcess::shortageGriggerSlot);
    connect(this, &AutoRunProcess::StopTheMachinesignals,
            this, &AutoRunProcess::StopTheMachineSlots);


    //GpioController::getInstance().pilotLampYellow();

}

void AutoRunProcess::plcStopEmit()
{
    LogDebug << "Start to plcStopEmit";
    plcStop_ = true;
}

void AutoRunProcess::setThreadPriority()
{
    pthread_t threadId = pthread_self();

    // 设置实时调度策略和优先级
    struct sched_param param;
    param.sched_priority = 90;  // 实时优先级，范围1-99，数值越高优先级越高
    if (pthread_setschedparam(threadId, SCHED_FIFO, &param) != 0) {
        qWarning() << "Failed to set AutoRunProcess real-time scheduling policy";
    }else
        qWarning() << "Sucessufl to set AutoRunProcess real-time scheduling policy";
}

void AutoRunProcess::continueProcess()
{

    skipOnce = true;
    qInfo() << " AutoRunProcess::continueProcess" ;
    plcStop_ = false;
    isInPlayce = true;
    GpioController::getInstance().plcStart();
    GpioController::getInstance().pilotLampGreen();

    if(FloorSetting::getInstance().get_replenishmentisModel() == 2)
    {
        FloorSetting::getInstance().replenishmentMonitor();
    }
    updateisRunning(true);
    updatesudentStop(false);
    if(inplaceStopLunch)
    {
        inplaceStopLunch = false;
        if(ImageProcessor::getInstance().get_InplaceModel() == 2)
        {
            MouseTracker::getInstance().getMoveDistance();
            ImageProcessor::getInstance().updatesetFabricSpacingTime(10);
            FabricSpacingList.clear();
        }

        {
            ImageProcessor::getInstance().updatesetMoveDistanceime(10);
            moveDistanceList.clear();
            moveDistanceMax = 9999;
            moveDistanceMin = -9999;
            ImageProcessor::getInstance().updatemoveDistanceMax(9999);
            ImageProcessor::getInstance().updatemoveDistanceMin(-9999);

        }
        isInPlayce = true;
    }
}

void AutoRunProcess::startProcess() {
    qDebug() << "自动运行流程已启动。";
    plcStop_ = false;
    receivedIO1 = 0;
    GpioController::getInstance().pilotLampGreen();
    //GpioController::getInstance().plcStart();
    connect(&GpioController::getInstance(), &GpioController::infrared1trigger,
            this, &AutoRunProcess::onIO1SignalReceived);
    connect(&GpioController::getInstance(), &GpioController::infrared2trigger,
            this, &AutoRunProcess::onIO2SignalReceived);
    connect(&GpioController::getInstance(), &GpioController::shortageGrigger,
            this, &AutoRunProcess::shortageGriggerSlot);
    connect(&AfterDetect::getInstance() , &AfterDetect::moveDistanceSign  ,
            this, &AutoRunProcess::moveDistanceSlot);

    // connect(&GpioController::getInstance(), &GpioController::inplaceGrigger,
    //         this, &AutoRunProcess::oninplaceGriggerReceived);
    if(FloorSetting::getInstance().get_replenishmentisModel() == 2)
    {
        FloorSetting::getInstance().replenishmentMonitor();
    }

    if(ImageProcessor::getInstance().get_InplaceModel() == 2)
    {
        MouseTracker::getInstance().getMoveDistance();
        ImageProcessor::getInstance().updatesetFabricSpacingTime(10);
        FabricSpacingList.clear();
    }

    {
        ImageProcessor::getInstance().updatesetMoveDistanceime(10);
        moveDistanceList.clear();
        moveDistanceMax = 9999;
        moveDistanceMin = -9999;
        ImageProcessor::getInstance().updatemoveDistanceMax(9999);
        ImageProcessor::getInstance().updatemoveDistanceMin(-9999);

    }

    QVector<int> vec = CvAlgEdgeDetection::getInstance().logoSizeErridList();
    CvAlgEdgeDetection::getInstance().setlogoSizeErridList(QVector<int>{});
    CvAlgEdgeDetection::getInstance().setlogoSizeErrNum(
        CvAlgEdgeDetection::getInstance().get_logoSizeContinuous());
    isInPlayce = true;

    updateisRunning(true);

}

void AutoRunProcess::stopProcess() {
    qDebug() << "自动运行流程已停止。";
    //receivedIO1 = 0;
    StopTheMachine();
    if(GpioController::getInstance().pilotLampStatus_ = GpioController::LAMP_GREEN)
        GpioController::getInstance().pilotLampYellow();
    GpioController::getInstance().plcStop();
    disconnect(&GpioController::getInstance(), &GpioController::infrared1trigger,
               this, &AutoRunProcess::onIO1SignalReceived);
    disconnect(&GpioController::getInstance(), &GpioController::infrared2trigger,
               this, &AutoRunProcess::onIO2SignalReceived);
    disconnect(&GpioController::getInstance(), &GpioController::shortageGrigger,
               this, &AutoRunProcess::shortageGriggerSlot);
    // disconnect(&GpioController::getInstance(), &GpioController::inplaceGrigger,
    //            this, &AutoRunProcess::oninplaceGriggerReceived);
    disconnect(&AfterDetect::getInstance() , &AfterDetect::moveDistanceSign  ,
               this, &AutoRunProcess::moveDistanceSlot);
    if (IO1debounceTimer->isActive()) {
        IO1debounceTimer->stop();
    }
    if (IO2debounceTimer->isActive()) {
        IO2debounceTimer->stop();
    }
}

//拍照
void AutoRunProcess::onIO1SignalReceived() {
    //qInfo() << "get onIO1SignalReceived";
    if(GpioController::getInstance().gpioDI1() == true)
    {
        QTimer::singleShot(2, this, [this](){
            if(GpioController::getInstance().gpioDI1() != true)
            {
                //qWarning() << "onIO1SignalReceived true False";
                return;
            }
            if (!IO1debounceTimer->isActive()) {
                if(receivedIO1 == 2 || receivedIO1 == 0)
                {
                    qInfo() << "DI 1 changed";

                    //LogTrackq << "接收到IO1信号，等待IO2信号...";
                    IO1debounceTimer->start(AntiShakeDelay); // 防抖动，50毫秒内不接受新的IO1信号

                    QVariantList signalList = ImageProcessor::getInstance().get_iO1SignalReceived();


                    detectContinous();

                    if(containsInt(signalList , 3 ))
                    {
                        //detectInplayce();
                    }

                    if(containsInt(signalList , 1 ))
                    {
                        //-------------step2 拍照运行
                        recordCallInterval();
                        AfterDetect::getInstance().addImageId();
                        int delaytime = ImageProcessor::getInstance().photographyDelay();
                        QTimer::singleShot(delaytime, this, [](){
                            ImageProcessor::getInstance().setcaptureImgMode(ImageProcessor::IOTriggered);
                        }); // 延迟后执行captureImgMode函数
                    }
                    if(containsInt(signalList , 2 ))
                    {
                        determineRemoveWaste();
                    }

                    //-------------自动运行处理函数------------------
                    //-------------step1 先判断是否排废
                    // determineRemoveWaste();
                    receivedIO1 = 1;
                }
            }
            else
                qWarning() << "onIO1SignalReceived IO1debounceTimer is active";
        });
    }else
        qWarning() << "onIO1SignalReceived gpioDI1  == False";
}

void AutoRunProcess::recordCallInterval() {
    // 获取当前时间
    QDateTime currentCallTime = QDateTime::currentDateTime();

    // 如果不是第一次调用，计算当前调用到上一次调用的时间间隔
    if (lastCallTime.isValid()) {
        int interval = lastCallTime.msecsTo(currentCallTime);  // 计算间隔时间（毫秒）
        intervalTimes.enqueue(interval);  // 将间隔时间入队

        // 如果队列长度超过 10，删除最旧的记录
        if (intervalTimes.size() > 10) {
            intervalTimes.dequeue();
        }
    }

    // 更新上次调用的时间
    lastCallTime = currentCallTime;

    int totalInterval = 0;

    // 计算过去 10 次调用的总间隔时间
    for (int interval : intervalTimes) {
        totalInterval += interval;
    }

    // 计算频率：总间隔时间 / 调用次数（每分钟调用次数）
    float frequency = (intervalTimes.size() > 0) ? (60000 / (totalInterval / intervalTimes.size())) : 0;
    ImageProcessor::getInstance().updatecapfrequency(frequency);
    // qInfo() << "Capture frequency in the last minute: " << frequency << " times.";

    // // 显示最近 10 次的调用间隔
    // qInfo() << "Last 10 call intervals (ms):";
    // for (int i = 0; i < intervalTimes.size(); ++i) {
    //     qInfo() << "Call " << (i + 1) << ": " << intervalTimes[i] << " ms";
    // }
}

//打料
void AutoRunProcess::onIO2SignalReceived() {
    //qInfo() << "get onIO2SignalReceived";
    if(GpioController::getInstance().gpioDI2() == true)
    {
        QTimer::singleShot(2, this, [this](){
            if(GpioController::getInstance().gpioDI2() != true)
            {
                //qWarning() << "onIO2SignalReceived true False";
                return;
            }
            if (!IO2debounceTimer->isActive()) {
                if(receivedIO1==1 || receivedIO1==0)
                {
                    qInfo() << "DI 2 changed";

                    // qDebug() << "接收到IO2信号，准备延迟执行图像处理函数...";
                    IO2debounceTimer->start(AntiShakeDelay);
                    detectContinous();

                    QVariantList signalList = ImageProcessor::getInstance().get_iO2SignalReceived();

                    if(containsInt(signalList , 3 ))
                    {
                        //detectInplayce();
                    }

                    if(containsInt(signalList , 1 ))
                    {
                        //-------------step2 拍照运行
                        recordCallInterval();
                        AfterDetect::getInstance().addImageId();
                        int delaytime = ImageProcessor::getInstance().photographyDelay();
                        QTimer::singleShot(delaytime, this, [](){
                            ImageProcessor::getInstance().setcaptureImgMode(ImageProcessor::IOTriggered);
                        }); // 延迟后执行captureImgMode函数
                    }
                    if(containsInt(signalList , 2 ))
                    {
                        determineRemoveWaste();
                    }

                    if(plcStop_)
                    {
                        qInfo() << "STOP SLC plcStop_";
                        if( GpioController::getInstance().gpioDI2() == true)
                        {
                            QTimer::singleShot(ImageProcessor::getInstance().get_plcStopDelay(), [this]() {
                                GpioController::getInstance().plcStop();
                                plcStop_ = false;
                                QTimer::singleShot(1000, [this]() {
                                    updateisRunning(false);
                                });
                                //GpioController::getInstance().setGpioDO2(true);
                                // QTimer::singleShot(50, [this]() {
                                //     // 50ms后拉低 GpioDO1
                                //     GpioController::getInstance().setGpioDO2(false);
                                //     emit StopTheMachinesignals();
                                // });
                            });
                        }
                    }
                }
                // QTimer::singleShot(3000, this, &AutoRunProcess::captureImgMode); // 3秒后执行captureImgMode函数
                receivedIO1 = 2;
            }
            else
                qWarning() << "onIO2SignalReceived IO1debounceTimer is active";

        });
    }else
        qWarning() << "onIO2SignalReceived gpioDI2  == False";
}

void AutoRunProcess::detectInplayce()
{
    qInfo() << "go in detectInplayce" ;
    // if( isInPlayce == true)
    if(ImageProcessor::getInstance().get_InplaceModel() == 2)
    {
        if(skipOnce || receivedIO1 == 0)
        {
            qInfo() << "skip once detectInplayce" ;
            skipOnce = false;
            MouseTracker::getInstance().getMoveDistance();
            return;
        }
        int setFabricSpacingTime = ImageProcessor::getInstance().setFabricSpacingTime();
        if(setFabricSpacingTime)
        {
            skipStepOver = 0;
            float distance = MouseTracker::getInstance().getMoveDistance();
            qInfo() << "distance: " << distance;
            FabricSpacingList.append(distance);
            setFabricSpacingTime --;
            if(setFabricSpacingTime == 0)
            {
                MouseTracker::getInstance().set_fabricSpacing(calculateMinValueWithExclusion(FabricSpacingList));
            }
            ImageProcessor::getInstance().updatesetFabricSpacingTime(setFabricSpacingTime);
        }else
        {
            switch (MouseTracker::getInstance().getMoveDistanceAct()) {
            case 1:

                DetectCacheModel::instance().inPlaceadjustCache(
                    AfterDetect::getInstance().getImageId(),
                    ImageProcessor::getInstance().get_trimminginterval() -
                        ImageProcessor::getInstance().get_wasteToCutting());
                AfterDetect::getInstance().inPlaceadjustCache(
                    AfterDetect::getInstance().getImageId(),
                    ImageProcessor::getInstance().get_trimminginterval() -
                        ImageProcessor::getInstance().get_wasteToCutting());

                skipStepOver ++ ;
                if(ImageProcessor::getInstance().get_InplaceIsStop() && skipStepOver >= 1)
                {
                    GpioController::getInstance().pilotLampRed();
                    GpioController::getInstance().pilotLampBuzzer();
                    skipStepOver = 0;
                    StopTheMachine();
                    inplaceStopLunch = true;
                    updatesudentStop(true);
                    emit inplaceSlidingStepSign();
                }

                break;
            case -1:
                // qWarning() << "get AutoRunProcess::detectInplayce" ;
                // AfterDetect::getInstance().inPlaceadjustCache(
                //     AfterDetect::getInstance().getImageId(),
                //     ImageProcessor::getInstance().get_trimminginterval() - ImageProcessor::getInstance().get_wasteToCutting());
                // GpioController::getInstance().pilotLampRed();
                // GpioController::getInstance().pilotLampBuzzer();
                // plcStop_ = true;
                // emit inplaceSign();
                // break;
            default:
                skipStepOver = 0;
                break;
            }
        }

    }else if(ImageProcessor::getInstance().get_InplaceModel() == 1)
    {
        if(GpioController::getInstance().gpioDI4() == true)
        {
            skipStepOver = 0;
            isInPlayce = false;
        }else
        {
            qWarning() << "get AutoRunProcess::detectInplayce" ;
            DetectCacheModel::instance().inPlaceadjustCache(
                AfterDetect::getInstance().getImageId(),
                ImageProcessor::getInstance().get_trimminginterval() -
                    ImageProcessor::getInstance().get_wasteToCutting());
            AfterDetect::getInstance().inPlaceadjustCache(
                AfterDetect::getInstance().getImageId(),
                ImageProcessor::getInstance().get_trimminginterval() -
                    ImageProcessor::getInstance().get_wasteToCutting());
            if(ImageProcessor::getInstance().get_InplaceIsStop() && skipStepOver >= 2)
            {
                GpioController::getInstance().pilotLampRed();
                GpioController::getInstance().pilotLampBuzzer();
                skipStepOver = 0;
                StopTheMachine();
                updatesudentStop(true);
                inplaceStopLunch = true;
                emit inplaceSign();
            }

        }
    }

}

void AutoRunProcess::oninplaceGriggerReceived()
{

    if(ImageProcessor::getInstance().get_inplaceShake() <= 0)
    {
        qInfo() << "DI 4 changed";
        isInPlayce = true;
    }else{
        //qInfo() << "get_InplaceShake():  " << ImageProcessor::getInstance().get_InplaceShake();
        QTimer::singleShot(ImageProcessor::getInstance().get_inplaceShake(), [this]() {
            if(GpioController::getInstance().gpioDI4() == true)
            {
                qInfo() << "DI 4 changed";
                isInPlayce = true;
            }
        });
    }
}

void AutoRunProcess::startPLC()
{
    plcStop_ = false;
    GpioController::getInstance().plcStart();
}

void AutoRunProcess::stopPLC()
{
    StopTheMachine();
}

void AutoRunProcess::RealTimestopPLC()
{
    GpioController::getInstance().plcStop();
}

void AutoRunProcess::moveDistanceSlot(float distance)
{
    if(ImageProcessor::getInstance().get_moveDistanceEnable())
    {
        ImageProcessor::getInstance().updatemoveDistance(distance);
        int setMoveDistanceime = ImageProcessor::getInstance().setMoveDistanceime();
        if(setMoveDistanceime)
        {
            moveDistanceList.append(distance);
            setMoveDistanceime --;
            if(setMoveDistanceime == 0)
            {
                calculateAdjustedRange(moveDistanceList);
                ImageProcessor::getInstance().updatemoveDistanceMax(moveDistanceMax);
                ImageProcessor::getInstance().updatemoveDistanceMin(moveDistanceMin);
            }
            ImageProcessor::getInstance().updatesetMoveDistanceime(setMoveDistanceime);
        }else
        {
            int distanceOvertime = ImageProcessor::getInstance().distanceOvertime();
            if(distance < moveDistanceMin || distance > moveDistanceMax)
            {

                distanceOvertime ++;
                if(ImageProcessor::getInstance().get_inplaceOverTimes()!=0 &&
                    distanceOvertime > ImageProcessor::getInstance().get_inplaceOverTimes())
                {
                    distanceOvertime = 0;
                    GpioController::getInstance().pilotLampRed();
                    GpioController::getInstance().pilotLampBuzzer();
                    //if(ImageProcessor::getInstance().get_InplaceIsStop())
                    qWarning() << "get moveDistanceSlot Error" << "" ;
                    StopTheMachine();
                    updatesudentStop(true);
                    inplaceStopLunch = true;
                    emit inplaceSign();
                }
            }else
            {
                distanceOvertime = 0;
            }
            ImageProcessor::getInstance().updatedistanceOvertime(distanceOvertime);
        }
    }
}


void AutoRunProcess::captureImgMode() {
    qDebug() << "图像处理函数已执行。";
    emit processingCompleted();
    // 在这里添加图像处理逻辑
}

void AutoRunProcess::detectContinous()
{
    if(sudentStop() == true  && isRunning() == false)
    {
        emit sudentStopContinue();
        skipOnce = true;
        qInfo() << " AutoRunProcess::detectContinous" ;
        plcStop_ = false;
        isInPlayce = true;

        GpioController::getInstance().pilotLampGreen();

        if(FloorSetting::getInstance().get_replenishmentisModel() == 2)
        {
            FloorSetting::getInstance().replenishmentMonitor();
        }
        updateisRunning(true);
        updatesudentStop(false);
        if(inplaceStopLunch)
        {
            inplaceStopLunch = false;
            if(ImageProcessor::getInstance().get_InplaceModel() == 2)
            {
                MouseTracker::getInstance().getMoveDistance();
                ImageProcessor::getInstance().updatesetFabricSpacingTime(10);
                FabricSpacingList.clear();
            }

            {
                ImageProcessor::getInstance().updatesetMoveDistanceime(10);
                moveDistanceList.clear();
                moveDistanceMax = 9999;
                moveDistanceMin = -9999;
                ImageProcessor::getInstance().updatemoveDistanceMax(9999);
                ImageProcessor::getInstance().updatemoveDistanceMin(-9999);

            }
            isInPlayce = true;
        }
    }
}

void AutoRunProcess::determineRemoveWaste()
{

    int RemoveIndex = AfterDetect::getInstance().getImageId()-
                      ImageProcessor::getInstance().get_trimminginterval();
    bool isRemove = AfterDetect::getInstance().getCacheWaste(RemoveIndex +
                                                             ImageProcessor::getInstance().get_waste2outlet());
    QVector<int> logosizeList = CvAlgEdgeDetection::getInstance().logoSizeErridList();

    int RemoveIndexdiff = RemoveIndex +
                          ImageProcessor::getInstance().get_speedDiff();


    LogTrack << "AutoRunProcess::determineRemoveWaste index:" << RemoveIndex << "[" << isRemove <<"]";
    if(isRemove)
    {
        QTimer::singleShot(ImageProcessor::getInstance().get_removeBaseDelay(), []() {
            GpioController::getInstance().setGpioDO9(true);
            QTimer::singleShot(ImageProcessor::getInstance().get_removeBaseDuration(), []() {
                // 50ms后拉低 GpioDO1
                GpioController::getInstance().setGpioDO9(false);
            });
        });
    }else
    {
        DetectCacheModel::instance().addOkNum();

        if( ((CvAlgEdgeDetection::getInstance().logoSizeEnable() == true &&
              CvAlgEdgeDetection::getInstance().get_logoSizeRefuelling() == true) == false)
            && ImageProcessor::getInstance().get_numberbatch() > 0
            && DetectCacheModel::instance().okNum() + ImageProcessor::getInstance().get_speedDiff()  >=
                   ImageProcessor::getInstance().get_numberbatch() )
        {
            LogDebug << "get AutoRunProcess::getarriveBatchGriggerSign" ;
            GpioController::getInstance().pilotLampRed();
            GpioController::getInstance().pilotLampBuzzer();
            StopTheMachine();
            DetectCacheModel::instance().clearOkNum();
            updatesudentStop(true);
            emit arriveBatchGriggerSign();
        }
    }

    if(CvAlgEdgeDetection::getInstance().get_logoSizeRefuelling() &&
        logosizeList.contains(RemoveIndexdiff))
    {
        GpioController::getInstance().pilotLampRed();
        GpioController::getInstance().pilotLampBuzzer();
        // CvAlgEdgeDetection::getInstance().setlogoSizeGone(false);
        // CvAlgEdgeDetection::getInstance().setlogoSizeErrid(-1);
        logosizeList.removeOne(RemoveIndexdiff);
        CvAlgEdgeDetection::getInstance().setlogoSizeErridList(logosizeList);
        StopTheMachine();
        isRemove = false;
        updatesudentStop(true);
        emit logosizeChangeSign();
    }
}

void AutoRunProcess::shortageGriggerSlot()
{
    if(GpioController::getInstance().gpioDI3() == false)
    {
        QTimer::singleShot(300, [this]() {
            // GpioController::getInstance().setGpioDO9(true);
            // QTimer::singleShot(ImageProcessor::getInstance().get_removeBaseDuration(), []() {
            //     // 50ms后拉低 GpioDO1
            //     GpioController::getInstance().setGpioDO9(false);
            // });
            if(GpioController::getInstance().gpioDI3() == false)
            {
                LogDebug << "get AutoRunProcess::shortageGriggerSlot" ;
                GpioController::getInstance().pilotLampRed();
                GpioController::getInstance().pilotLampBuzzer();
                StopTheMachine();
                updatesudentStop(true);
                emit shortageGriggerSign();

            }
            //GpioController::getInstance().plcStop();
        });

    }
}

void AutoRunProcess::StopTheMachineSlots()
{
    LogDebug << "Machine has been emit";
    stopProcess();
}

void AutoRunProcess::StopTheMachine()
{
    LogDebug << "Attempting to stop machine";
    plcStop_ = true;
}
